const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");

// 配置 multer
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/images/') // 确保这个目录存在
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname))
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 20 * 1024 * 1024 // 限制文件大小为20MB
  }
}).single('file'); // 'file' 要和前端 formData.append 的第一个参数对应

router.post("/upload", (req, res) => {
  upload(req, res, function(err) {
    if (err) {
      return res.status(500).json({
        code: 500,
        message: "上传失败",
        error: err.message
      });
    }
    
    // 上传成功
    res.json({
      code: 200,
      message: "上传成功",
      result: {
        url: `/public/images/${req.file.filename}`,
        img: `${process.env.BASE_URL}/public/images/${req.file.filename}`
      }
    });
  });
});

module.exports = router;